<template>
  <div class="divBox relative">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-tabs
          v-if="checkPermi(['merchant:product:tabs:headers'])"
          v-model="tableFrom.type"
          @tab-click="getList(1)"
        >
          <el-tab-pane
            v-for="(item, index) in headerName"
            :key="index"
            :label="item.name + '(' + item.count + ')'"
            :name="item.type.toString()"
          />
        </el-tabs>
        <div class="container mt-1">
          <el-form inline size="small">
            <el-form-item :label="$t('pingTaiDuanShangPinFenLei')">
              <el-cascader
                v-model="tableFrom.categoryId"
                :options="translateNameProductClassify"
                :props="props2"
                clearable
                filterable
                class="selWidth mr20"
                size="small"
                @change="seachList"
              />
            </el-form-item>
            <el-form-item :label="$t('shangPinSouSuo')">
              <el-input
                v-model="tableFrom.keywords"
                :placeholder="$t('qingShuRuShangPinMingChengGuanJianZi')"
                class="selWidth"
                size="small"
                clearable
              >
                <el-button
                  slot="append"
                  v-hasPermi="['merchant:product:page:list']"
                  icon="el-icon-search"
                  size="small"
                  @click="seachList"
                />
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <router-link :to="{ path: '/product/list/creatProduct' }">
          <el-button v-hasPermi="['merchant:product:save']" size="small" type="primary" class="mr10">{{
            $t('tianJiaShangPin')
          }}</el-button>
        </router-link>
        <el-button type="primary" size="small" @click="bulkImportFn">{{ $t('piLiangXinZeng') }}</el-button>
        <el-button type="primary" size="small" @click="batchUpdateFn">{{ $t('piLiangGengXin') }}</el-button>
        <el-button type="primary" size="small" @click="exportFn">导出</el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="tableData.data"
        style="width: 100%"
        size="mini"
        :highlight-current-row="true"
        :header-cell-style="{ fontWeight: 'bold' }"
        row-key="id"
        @selection-change="onSelectTab"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item :label="$t('shouCang')">
                <span>{{ props.row.collectCount }}</span>
              </el-form-item>
              <el-form-item :label="$t('xuNiXiaoLiang')">
                <span>{{ props.row.ficti }}</span>
              </el-form-item>
              <el-form-item :label="$t('juJueYuanYin')">
                <span>{{ props.row.reason }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column v-if="checkedCities.includes('ID')" prop="id" label="ID" min-width="50" />
        <el-table-column v-if="checkedCities.includes('shangPinTu')" :label="$t('shangPinTu')" min-width="80">
          <template slot-scope="scope">
            <div class="demo-image__preview">
              <el-image
                style="width: 36px; height: 36px"
                :src="scope.row.image"
                :preview-src-list="[scope.row.image]"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('shangPinMingCheng')"
          :label="$t('shangPinMingCheng')"
          prop="storeName"
          min-width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          v-if="checkedCities.includes('pingTaiDuanShangPinFenLei')"
          :label="$t('pingTaiDuanShangPinFenLei')"
          prop="categoryId"
          align="center"
          min-width="140"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <el-tag class="tag">
              {{ scope.row.categoryName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('shangPinShouJia')"
          prop="price"
          :label="$t('shangPinShouJia')"
          min-width="90"
          align="center"
        />
        <el-table-column
          v-if="checkedCities.includes('xiaoLiang')"
          prop="sales"
          :label="$t('xiaoLiang')"
          min-width="90"
          align="center"
        />
        <el-table-column
          v-if="checkedCities.includes('actualInventory')"
          prop="stock"
          :label="$t('actualInventory')"
          min-width="90"
          align="center"
        />
        <el-table-column
          v-if="checkedCities.includes('paiXu')"
          prop="sort"
          :label="$t('paiXu')"
          min-width="70"
          align="center"
        />
        <el-table-column
          v-if="checkedCities.includes('shiFouTongBu')"
          prop="syncImlFlag"
          :label="$t('shiFouTongBu')"
          min-width="90"
          align="center"
        >
          <template slot-scope="scope">
            {{ scope.row.syncImlFlag === 'Y' ? $t('yes') : $t('no') }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkedCities.includes('tongBuShiJian')"
          prop="syncImlTime"
          :label="$t('tongBuShiJian')"
          min-width="90"
          align="center"
        />
        <el-table-column
          v-if="checkedCities.includes('tongBuYiChang')"
          prop="syncImlExceptionMsg"
          :label="$t('tongBuYiChang')"
          min-width="90"
          align="center"
        />
        <el-table-column
          :label="$t('caoZuo')"
          min-width="150"
          fixed="right"
          align="center"
          :render-header="renderHeader"
        >
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['merchant:product:info']"
              type="text"
              size="small"
              @click="handleAudit(scope.row.id, false)"
            >{{ $t('xiangQing') }}</el-button>
            <!-- <router-link :to="{ path: '/product/list/creatProduct/' + scope.row.id + '/1' }">
              <el-button type="text" size="small" class="mr10" v-hasPermi="['merchant:product:info']">详情</el-button>
            </router-link> -->
            <el-button
              v-if="['1','2','3','9','10'].includes(tableFrom.type)"
              v-hasPermi="['merchant:product:update']"
              type="text"
              size="small"
              @click="editFn(scope.row.id)"
            >{{ $t('bianJi') }}</el-button>
            <el-button
              v-if="['6'].includes(tableFrom.type)"
              v-hasPermi="['merchant:product:restore']"
              type="text"
              size="small"
              @click="handleRestore(scope.row.id, scope.$index)"
            >{{ $t('huiFuShangPin') }}</el-button>
            <el-button
              v-if="['6','2','3'].includes(tableFrom.type)"
              v-hasPermi="['merchant:product:delete']"
              type="text"
              size="small"
              @click="handleDelete(scope.row.id, tableFrom.type)"
            >{{ tableFrom.type === '6' ? $t('shanchu') : $t('jiaruhuishouzhan') }}</el-button>
            <el-button
              v-if="['4','5','8','11'].includes(tableFrom.type)"
              type="text"
              size="small"
              @click="updateStockFn(scope.row)"
            >{{ $t('gengXinKuCun') }}</el-button>
            <el-button
              v-if="['2','11'].includes(tableFrom.type)&&['UN_SYNC','ARCHIVE'].includes(scope.row.syncStatus)"
              v-hasPermi="['merchant:product:up']"
              type="text"
              size="small"
              @click="putOnShell(scope.row)"
            >{{ $t('shangjia') }}</el-button>
            <el-button
              v-if="['8'].includes(tableFrom.type)"
              v-hasPermi="['merchant:product:down']"
              type="text"
              size="small"
              @click="offShell(scope.row)"
            >{{ $t('xiajia') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[20, 40, 60, 80,200]"
          :page-size="tableFrom.limit"
          :current-page="tableFrom.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>
    <div v-show="card_select_show" class="card_abs">
      <div class="cell_ht">
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">{{
          $t('quanXuan')
        }}</el-checkbox>
        <el-button type="text" @click="checkSave()">{{ $t('baoCun') }}</el-button>
      </div>
      <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
        <el-checkbox v-for="item in columnData" :key="item" :label="item" class="check_cell">{{
          $t(item)
        }}</el-checkbox>
      </el-checkbox-group>
    </div>
    <el-dialog
      :title="$t('fuZhiTaoBaoTianMaoJingDongSuNing')"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="1200px"
      class="taoBaoModal"
      :before-close="handleClose"
    >
      <tao-bao v-if="dialogVisible" @handleCloseMod="handleCloseMod" />
    </el-dialog>

    <info-from ref="infoFrom" :is-atud="isAtud" :is-show="isShow" :product-id="productId" @subSuccess="subSuccess" />
    <bulkImportDialog ref="bulkImportDialog" @getList="getList(1)" />
    <batchUpdateDialog ref="batchUpdateDialogRef" @getList="getList(1)" />

    <updateStockDialog ref="updateStockRef" @getList="getList" />
  </div>
</template>

<script>
import {
  // storeCategoryAllApi,
  productLstApi,
  productDeleteApi,
  // categoryApi,
  putOnShellApi,
  offShellApi,
  productHeadersApi,
  // productExportApi,
  restoreApi,
  productExcelApi,
  syncOmsApi,
  exportExcelApi
} from '@/api/store'
// import { getToken } from '@/utils/auth'
import taoBao from './taoBao'
import { checkPermi } from '@/utils/permission' // 权限判断函数
import { mapGetters } from 'vuex'
import infoFrom from './info'
import bulkImportDialog from '@/components/importDialog/bulkImportDialog'
import batchUpdateDialog from '@/components/importDialog/batchUpdateDialog'
import Cookies from 'js-cookie'
import { mapToid } from '@/utils/index.js'
import updateStockDialog from './dialog/updateStock'
export default {
  name: 'ProductList',
  directives: {
    // 计算是否滚动到最下面
    selectLoadMore: {
      bind(el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
        SELECTWRAP_DOM.addEventListener('scroll', function() {
          if (this.scrollHeight - this.scrollTop < this.clientHeight + 1) {
            binding.value()
          }
        })
      }
    }
  },
  components: { taoBao, infoFrom, bulkImportDialog, batchUpdateDialog, updateStockDialog },
  data() {
    return {
      isAtud: false,
      isShow: false,
      productId: 0,
      props1: {
        children: 'childList',
        label: 'name',
        value: 'id',
        multiple: false,
        emitPath: false
      },
      props2: {
        children: 'childList',
        label: 'translateName',
        value: 'id',
        multiple: false,
        emitPath: false,
        checkStrictly: true
      },
      // roterPre: roterPre,
      headeNum: [],
      listLoading: true,
      tableData: {
        data: [],
        total: 0
      },
      tableFrom: {
        page: 1,
        limit: 20,
        keywords: '',
        type: '1'
      },
      categoryList: [],
      objectUrl: process.env.VUE_APP_BASE_API,
      dialogVisible: false,
      card_select_show: false,
      checkAll: false,
      checkedCities: [
        'ID',
        'shangPinTu',
        'shangPinMingCheng',
        'pingTaiDuanShangPinFenLei',
        'shangPinShouJia',
        'xiaoLiang',
        'actualInventory',
        'paiXu'
      ],
      // 'shiFouTongBu', 'tongBuShiJian', 'tongBuYiChang'
      columnData: [
        'ID',
        'shangPinTu',
        'shangPinMingCheng',
        'pingTaiDuanShangPinFenLei',
        'shangPinShouJia',
        'xiaoLiang',
        'actualInventory',
        'paiXu'
      ],
      // 'shiFouTongBu', 'tongBuShiJian', 'tongBuYiChang'
      isIndeterminate: true,
      headerName: [{
        name: this.$t('daiShenHe'),
        type: 1,
        count: 0
      }, {
        name: this.$t('cangKuZhong'),
        type: 2,
        count: 0
      }, {
        name: this.$t('shenHeShiBai'),
        type: 3,
        count: 0
      },
      // {
      //   name: this.$t('yiShouQing'),
      //   type: 4,
      //   count: 0
      // }, {
      //   name: this.$t('jingJieKuCun'),
      //   type: 5,
      //   count: 0
      // },
      {
        name: this.$t('huiShouZhan'),
        type: 6,
        count: 0
      }, {
        name: this.$t('tongBuDaiShenHe'),
        type: 7,
        count: 0
      }, {
        name: this.$t('yiTongBu'),
        type: 8,
        count: 0
      }, {
        name: this.$t('tongBuJuJue'),
        type: 9,
        count: 0
      }, {
        name: this.$t('tongBuYiShanChu'),
        type: 10,
        count: 0
      }, {
        name: this.$t('tongBuWuKuCun'),
        type: 11,
        count: 0
      }],
      selectionList: []
    }
  },
  computed: {
    ...mapGetters([
      'adminProductClassify',
      // 'merProductClassify',
      // 'merProductClassifyArr',
      'productBrand',
      'translateNameProductClassify',
      'translateMerProductClassifyArr',
      'translateAdminProductClassifyArr'
    ])
  },
  activated() {
    this.getList()
  },
  async mounted() {
    this.checkedCities = this.$cache.local.has('goods_stroge')
      ? this.$cache.local.getJSON('goods_stroge')
      : this.checkedCities
    this.$store.dispatch('product/getAdminProductClassify')
    // if (!this.merProductClassify.length) this.$store.dispatch('product/getMerProductClassify')
    if (!this.productBrand.length) this.$store.dispatch('product/getMerProductBrand')
    if (!this.translateAdminProductClassifyArr.length) await this.$store.dispatch('product/getAdminProductClassify')

    this.getList()
  },
  methods: {
    checkPermi,
    handleRestore(id) {
      this.$modalSure(this.$t('huiFuShangPin')).then(() => {
        this.listLoading = true
        restoreApi(id).then((res) => {
          this.$message.success(this.$t('caoZuoChengGong'))
          this.getList()
          this.listLoading = false
        }).catch(() => {
          this.listLoading = false
        })
      })
    },
    seachList() {
      this.tableFrom.page = 1
      this.getList()
    },
    handleClose() {
      this.dialogVisible = false
    },
    // 导出
    exports() {
      productExcelApi({
        cateId: this.tableFrom.cateId,
        keywords: this.tableFrom.keywords,
        type: this.tableFrom.type
      }).then((res) => {
        window.location.href = res.fileName
      })
    },
    changeNodes(data) {
      if (data.length > 0) {
        for (var i = 0; i < data.length; i++) {
          if (!data[i].childList || data[i].childList.length < 1) {
            data[i].childList = undefined
          } else {
            this.changeNodes(data[i].childList)
          }
        }
      }
      return data
    },
    // 列表
    getList() {
      this.listLoading = true
      productLstApi(this.tableFrom)
        .then((res) => {
          for (let index = 0; index < this.headerName.length; index++) {
            for (let i = 0; i < res.tabsHeaderList.length; i++) {
              if (this.headerName[index].type === res.tabsHeaderList[i].type) {
                this.headerName[index].count = res.tabsHeaderList[i].count
                break
              }
            }
          }

          this.tableData.data = res.pageInfo.list.map(item => {
            item.categoryName = this.getCategoryName(item.categoryId)
            return item
          })
          this.tableData.total = res.pageInfo.total
          this.listLoading = false
        })
        .catch((res) => {
          this.listLoading = false
          this.$message.error(res.message)
        })
    },
    getCategoryName(categoryId) {
      const obj = this.translateAdminProductClassifyArr.find((e) => {
        return e.id == categoryId
      })
      return obj ? obj.translateName : ''
    },
    pageChange(page) {
      this.tableFrom.page = page
      this.getList()
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val
      this.getList()
    },
    // 删除
    handleDelete(id, type) {
      this.$modalSure(
        type == 6 ? this.$t('shanChuIdWeiIdDeShangPin', [id]) : this.$t('idWeiIdDeShangPinJiaRuHuiShouZhanMa', [id])
      ).then(() => {
        this.listLoading = true
        const deleteFlag = type == 6 ? 'delete' : 'recycle'
        productDeleteApi(id, deleteFlag).then(() => {
          this.$message.success(this.$t('shanChuChengGong'))
          this.getList()
          this.listLoading = false
        }).catch(() => {
          this.listLoading = false
        })
      })
    },
    // 上架
    putOnShell(row) {
      this.$modalSure(this.$t('shangjia')).then(() => {
        this.listLoading = true
        putOnShellApi(row.id)
          .then(() => {
            this.$message.success(this.$t('shangJiaChengGong'))
            this.getList()
            this.listLoading = false
          })
          .catch(() => {
            row.isShow = !row.isShow
            this.listLoading = false
          })
      })
    },
    // 下架
    offShell(row) {
      this.$modalSure(this.$t('xiajia')).then(() => {
        this.listLoading = true
        offShellApi(row.id)
          .then(() => {
            this.$message.success(this.$t('xiaJiaChengGong'))
            this.getList()
            this.listLoading = false
          })
          .catch(() => {
            row.isShow = !row.isShow
            this.listLoading = false
          })
      })
    },
    renderHeader(h) {
      return (
        <p>
          <span style='padding-right:5px;'>{this.$t('caoZuo')}</span>
          <i class='el-icon-setting' onClick={() => this.handleAddItem()}></i>
        </p>
      )
    },
    handleAddItem() {
      if (this.card_select_show) {
        this.$set(this, 'card_select_show', false)
      } else if (!this.card_select_show) {
        this.$set(this, 'card_select_show', true)
      }
    },
    handleCloseMod(item) {
      this.dialogVisible = item
      this.getList()
    },
    // 复制
    onCopy() {
      this.dialogVisible = true
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.columnData : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.columnData.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.columnData.length
    },
    checkSave() {
      this.$set(this, 'card_select_show', false)
      this.$modal.loading(this.$t('zhengZaiBaoCunDaoBenDiQingShaoHou'))
      this.$cache.local.setJSON('goods_stroge', this.checkedCities)
      setTimeout(this.$modal.closeLoading(), 1000)
    },
    subSuccess() {
      this.getList('')
    },
    handleAudit(id, c) {
      this.productId = id
      this.$refs.infoFrom.dialogVisible = true
      this.isShow = true
      this.isAtud = c
      this.$refs.infoFrom.getInfo(id)
    },
    // 同步
    syncFn(row) {
      console.log(row)
      syncOmsApi(JSON.parse(Cookies.get('JavaMerInfo')).id).then(() => {
        this.$message.success(this.$t('caoZuoChengGong'))
        this.getList()
      })
    },
    bulkImportFn() {
      this.$refs.bulkImportDialog.show()
    },
    // 批量更新
    batchUpdateFn() {
      this.$refs.batchUpdateDialogRef.show()
    },
    updateStockFn(row) {
      this.$refs.updateStockRef.show(row)
    },
    editFn(id) {
      this.$router.push(`/product/list/creatProduct/${id}`)
    },
    // 全选
    onSelectTab(selection) {
      this.selectionList = selection
    },
    exportFn() {
      const productIdList = this.selectionList.map(it => it.id)
      exportExcelApi({ ...this.tableFrom, productIdList }).then(res => {
        const blob = new Blob([res.file], { type: 'application/octet-stream' })// res.data为文件流文件
        console.log(blob)
        this.$download.saveAs(blob, res.fileName)
      })
    }
  }
}
</script>

<style scoped lang="scss">
.el-table__body {
  width: 100%;
  table-layout: fixed !important;
}
.taoBaoModal {
  //  z-index: 3333 !important;
}
.demo-table-expand {
  ::v-deep label {
    width: 82px;
  }
}
.demo-table-expand {
  ::v-deep .el-form-item__content {
    width: 77%;
  }
}
.selWidth {
  width: 350px !important;
}
.seachTiele {
  line-height: 30px;
}
.relative {
  position: relative;
}
.card_abs {
  position: absolute;
  padding-bottom: 15px;
  top: 260px;
  right: 40px;
  width: 200px;
  background: #fff;
  z-index: 99999;
  box-shadow: 0px 0px 14px 0px rgba(0, 0, 0, 0.1);
}
.cell_ht {
  height: 50px;
  padding: 15px 20px;
  box-sizing: border-box;
  border-bottom: 1px solid #eeeeee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.check_cell {
  width: 100%;
  padding: 15px 20px 0;
}
.mt-1 {
  margin-top: 6px;
}
::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #606266;
}

.infoBox {
  ::v-deep.el-drawer__header {
    margin-bottom: 0;
    font-size: 20px;
  }
  ::v-deep .el-input.is-disabled .el-input__inner {
    background: none;
    cursor: none;
    color: #606266;
    border: none !important;
  }
  ::v-deep.el-icon-arrow-down,
  ::v-deep .el-icon-arrow-up {
    display: none;
  }
}

.tag + .tag {
  margin-left: 10px;
}
</style>
